package com.zjff.show.zjffshow.tool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeTool {
    /*
         序列化 讲JAVA对象转换成字节码
     */
    public static byte[] Serialize(Object object){
        ObjectOutputStream oos = null;//输出流
        ByteArrayOutputStream bos = null;//输出字节流
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(object);//输出字节码
            byte[] bytes = bos.toByteArray();//讲字节码转换成比特流
            System.out.println("转换成功！");
            return bytes;
        }catch (Exception e){
            System.out.println("系统错误"+e.getMessage());
        }
        System.out.println("转换失败");
        return null;
    }
    /*
         反序列化(二进制码转成Object)
     */
    public static Object UnSerialize(byte[] bytes){
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);//将二进制码转换成对象
            System.out.println("反序列化成功");
            return ois.readObject();//返回objec对象
        }catch (Exception e){
            System.out.println("反序列化失败"+e.getMessage());
        }
        System.out.println("反序列化错误");
        return null;
    }
}
